﻿using System;
using System.Threading.Tasks;

namespace ARchGL.Platform.Utils
{
    /// <summary>
    /// 缓存，时间到期重新查询
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class TimerCache<T>
    {
        public DateTime GetTime = DateTime.UtcNow;
        public T Data;

        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="seconds">过期时间，单位秒</param>
        /// <param name="func"></param>
        /// <returns></returns>
        public T Get(float seconds, Func<T> func)
        {
            if (DateTime.UtcNow.Subtract(GetTime).TotalMilliseconds >= seconds * 1000 || Data == null)
            {
                Data = func();
                GetTime = DateTime.UtcNow;
            }
            return Data;
        }

        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="seconds">过期时间，单位秒</param>
        /// <param name="func"></param>
        /// <returns></returns>
        public async Task<T> GetAsync(float seconds, Func<Task<T>> func)
        {
            if (DateTime.UtcNow.Subtract(GetTime).TotalMilliseconds >= seconds * 1000 || Data == null)
            {
                Data = await func();
                GetTime = DateTime.UtcNow;
            }
            return Data;
        }
    }
}
